package com.tiancheng.trade.order.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.tiancheng.trade.order.bo.excel.ExportExcelBO;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;


public final class ExcelBuildUtil {

    /**
     * 根据list生成excel
     */
    public static void easyExcel(List<List<String>> head, List<List<Object>> data, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=data.xlsx");
        EasyExcel.write(response.getOutputStream()).head(head).sheet("sheet1").doWrite(data);
    }

    /**
     * 导出excel
     * @param baseBO
     * @param response
     */
    public static void exportExcel(ExportExcelBO baseBO, HttpServletResponse response)  throws IOException{
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=data.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        for (int i = 0; i < baseBO.getSheets().size(); i++) {
            // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。这里注意DemoData.class 可以每次都变，我这里为了方便 所以用的同一个class 实际上可以一直变
            WriteSheet writeSheet = EasyExcel.writerSheet(i, baseBO.getSheets().get(i).getSheetName()).head(baseBO.getSheets().get(i).getData().get(0).getClass()).build();
            // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
            excelWriter.write(baseBO.getSheets().get(i).getData(), writeSheet);
        }
        excelWriter.finish();
    }
}
